the most reliable and correct method to get network interface address in Linux using Perl


/ Published in: Perl
Save to your folder(s)

This method doesn't rely on parsing 'ifconfig' tool output, and should work in any Linux distribution, but also could work in other POSIX environments.
The function returns a string with IPv4 address or 'undef' if it's not possible.


Copy this code and paste it in your HTML
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Socket;
  5. require 'sys/ioctl.ph';
  6.  
  7. print get_interface_address('eth0');
  8.  
  9. sub get_interface_address
  10. {
  11. my ($iface) = @_;
  12. my $socket;
  13. socket($socket, PF_INET, SOCK_STREAM, (getprotobyname('tcp'))[2]) || die "unable to create a socket: $!\n";
  14. my $buf = pack('a256', $iface);
  15. if (ioctl($socket, SIOCGIFADDR(), $buf) && (my @address = unpack('x20 C4', $buf)))
  16. {
  17. return join('.', @address);
  18. }
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.